package kordegi.forumsystem.shiro;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import io.jsonwebtoken.lang.Assert;
import kordegi.forumsystem.entity.User;
import kordegi.forumsystem.service.Impl.UserServiceImpl;
import kordegi.forumsystem.service.UserService;
import kordegi.forumsystem.util.JwtUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author kordegi
 * @date 2022.05.03 15:52
 * @Description
 */

@Slf4j
@Component
public class UserRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    /**
     * @Description 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * @Description 识别该使用哪种realm
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * @Description 认证
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        //jwt token
        JwtToken jwt = (JwtToken) authenticationToken;
        log.info("jwt----", jwt);
        // 得到此token的权限和主体
        String userId = jwtUtils.getClaimsByToken((String) jwt.getPrincipal()).getSubject();
        User user = userService.getById(Long.parseLong(userId));

        //认定账户合法性
        if (user == null) throw new UnknownAccountException("账户不存在");
        if (user.getStatus() == -1) throw new LockedAccountException("账户已被锁定");

        //把user的权限赋给userProfile
        UserProfile userProfile = new UserProfile();
        BeanUtils.copyProperties(user, userProfile);
        log.info("profile--", userProfile.toString());

        return new SimpleAuthenticationInfo(userProfile, jwt.getCredentials(), getName());
    }
}
